package com.lu.lupicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.lupicturebackend.api.aliyunai.AliYunAiApi;
import com.lu.lupicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.lu.lupicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.lu.lupicturebackend.exception.BusinessException;
import com.lu.lupicturebackend.exception.ErrorCode;
import com.lu.lupicturebackend.exception.ThrowUtils;
import com.lu.lupicturebackend.manager.CosManager;
import com.lu.lupicturebackend.manager.upload.FilePictureUpload;
import com.lu.lupicturebackend.manager.upload.PictureUploadTemplate;
import com.lu.lupicturebackend.manager.upload.UrlPictureUpload;
import com.lu.lupicturebackend.model.dto.file.UploadPictureResult;
import com.lu.lupicturebackend.model.dto.picture.*;
import com.lu.lupicturebackend.model.entity.Picture;
import com.lu.lupicturebackend.model.entity.Space;
import com.lu.lupicturebackend.model.entity.User;
import com.lu.lupicturebackend.model.enums.PictureReviewStatusEnum;
import com.lu.lupicturebackend.model.vo.PictureVO;
import com.lu.lupicturebackend.model.vo.UserVO;
import com.lu.lupicturebackend.service.PictureService;
import com.lu.lupicturebackend.mapper.PictureMapper;
import com.lu.lupicturebackend.service.SpaceService;
import com.lu.lupicturebackend.service.UserService;
import com.lu.lupicturebackend.utils.ColorTransformer;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.lu.lupicturebackend.utils.ColorSimilarUtils.calculateSimilarity;

/**
 * @author 86186
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-05-30 10:36:16
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {
//    @Resource
//    private FileManager fileManager;

    @Resource
    private UserService userService;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private CosManager cosManager;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 上传图片
     *
     * @param inputSource
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        if (pictureUploadRequest == null) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        // 判断用户是否登录
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);

        // 校验空间
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            //  判断空间是否属于当前用户,或者有权限
            ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权限");
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 判断是新增还是修改

        if (pictureUploadRequest.getId() != null) {  // 修改
            Long id = pictureUploadRequest.getId();
            // 查询数据库
            Picture oldPicture = this.getById(id);
            if (oldPicture == null) { //　
                ThrowUtils.throwIf(true, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            }
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                if (!oldPicture.getSpaceId().equals(spaceId)) {
                    ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR, "空间id不一致");
                }
            }
        }
        // 新增
        // 上传，按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
//        UploadPictureResult uploadPictureResult = fileManager.uploadPictureFile(multipartFile, uploadPathPrefix);
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPictureFile(inputSource, uploadPathPrefix);
        // 构造对象存入数据库
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        // 缩略图url
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        // 设置主色调
        picture.setPicColor(ColorTransformer.colorTranspose(uploadPictureResult.getPicColor()));
        picture.setSpaceId(spaceId);
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        // 操作数据库
        // 如果pictureID  不为空，则修改
        if (pictureUploadRequest.getId() != null) {
            picture.setId(pictureUploadRequest.getId());
            picture.setEditTime(new Date());
        }
        //　填充审核参数
        this.fillReviewParams(picture, loginUser);
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean save = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "更新空间信息失败");
            }
            return true;
        });

        // 更新空间额度

        return PictureVO.objToVo(picture);
    }

    /**
     * 获取图片查询
     *
     * @param pictureQueryRequest
     * @return
     */

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        //　空间
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();

        // 编辑时间
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // 空间查询
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");

        // 时间查询
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime); //>=
        queryWrapper.le(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime); // <

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 图片脱敏 (脱敏)
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     *
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        // 获取图片列表
        List<Picture> pictureList = picturePage.getRecords();
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 将图片列表转为图片VO列表
        List<PictureVO> pictureVOList = pictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        // 获取用户信息
        Set<Long> collect = pictureList.stream()
                .map(Picture::getUserId)
                .collect(Collectors.toSet());
        // 查询用户信息
        Map<Long, List<User>> userMap = userService.listByIds(collect) // where id in (1,2,3)
                .stream().collect(Collectors.groupingBy(User::getId));
        // 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            if (userId != null && userId > 0) {
                List<User> users = userMap.get(userId);
                if (CollUtil.isNotEmpty(users)) {
                    User user = users.get(0);
                    UserVO userVO = userService.getUserVO(user);
                    pictureVO.setUser(userVO);
                }
            }
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 校验图片数据
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(pictureReviewRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        Long reviewRequestId = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum enumByValue = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (enumByValue == null || reviewStatus == null || PictureReviewStatusEnum.REVIEWING.equals(enumByValue)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "参数错误");
        }
        // 判断是否存在图片
        Picture OldPicture = this.getById(reviewRequestId);
        ThrowUtils.throwIf(OldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        // 审核状态是否重复
        ThrowUtils.throwIf(OldPicture.getReviewStatus().equals(reviewStatus), ErrorCode.PARAMS_ERROR, "审核状态重复");
        // 数据库操作
        Picture UpdatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, UpdatePicture);
        // 更新审核状态
        UpdatePicture.setReviewerId(loginUser.getId());
        UpdatePicture.setReviewTime(new Date());
        boolean result = this.updateById(UpdatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEW_PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer batchUploadPicture(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 1.校验参数
        ThrowUtils.throwIf(pictureUploadByBatchRequest.getCount() > 30, ErrorCode.PARAMS_ERROR, "最多30张图片");

        // 2.抓取内容
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("图片抓取失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片抓取失败");
        }
        // 3.解析内容
        Element div = document.getElementsByClass("dgControl").first();
        ThrowUtils.throwIf(div == null, ErrorCode.SYSTEM_ERROR, "获取元素失败");
        Elements imgElements = div.select("img");
        //　遍历元素,
        int uploadCount = 0;
        for (Element imgElement : imgElements) {
            String fileUrl = imgElement.attr("src");
            if (fileUrl.isEmpty()) {
                log.error("图片地址为空");
            }
            // 处理图片地址，防止转义和对象存储冲突的问题
            int i = fileUrl.indexOf("?");
            if (i > -1) {
                fileUrl = fileUrl.substring(0, i);
            }
            // 4.上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileUrl);
            String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
            if (StrUtil.isBlank(namePrefix)) {
                namePrefix = searchText;
            }

            try {
                if (StrUtil.isNotBlank(namePrefix)) {
                    // 设置图片名称，序号连续递增
                    pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
                }
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功,id={}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败,erro = {} ", e);
                continue;
            }
            if (uploadCount >= pictureUploadByBatchRequest.getCount()) {
                break;
            }
        }


        return uploadCount;
    }

    /**
     * 清理对象图片
     *
     * @param oldPicture
     */
    @Async
    @Override
    public void deletePicture(Picture oldPicture) {
        String oldPictureUrl = oldPicture.getUrl();
        // 判断该图片是否被多个记录使用
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        Long count = lambdaQuery()
                .eq(Picture::getUrl, oldPictureUrl)
                .count();
        ThrowUtils.throwIf(count > 1, ErrorCode.SYSTEM_ERROR, "图片被多个记录使用，请先删除该图片的记录");
        // 删除图片
        cosManager.deleteObject(oldPictureUrl);

        if (oldPicture.getThumbnailUrl() != null) {
            // 删除缩略图
            cosManager.deleteObject(oldPicture.getThumbnailUrl());
        }

    }

    /**
     * 空间权限校验
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        Long userId = loginUser.getId();
        if (spaceId == null) {
            //　公共图库只有本人和管理员有权限
            if (!userService.isAdmin(loginUser) && !userId.equals(picture.getUserId())) {
                ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间
            if (!userId.equals(picture.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    /**
     * 删除图片
     *
     * @param id
     * @param loginUser
     */
    @Override
    public void deletePicture(Long id, User loginUser) {
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        // 只有管理员或者图片上传者才允许删除
        if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR);
        }
        // 已经改为注解鉴权
//        this.checkPictureAuth(oldPicture, loginUser);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean b = this.removeById(id);
            ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR, "删除失败");
            boolean update = spaceService.lambdaUpdate()
                    .eq(Space::getId, oldPicture.getSpaceId())
                    .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                    .setSql("totalCount = totalCount - 1")
                    .update();
            ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
            return true;
        });
        this.deletePicture(oldPicture);
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, HttpServletRequest request) {

        // 开始构造图片对象
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 权限校验
        User loginUser = userService.getLoginUser(request);
        Picture oldPicture = this.getById(pictureEditRequest.getId());
        //  只有管理员或者图片上传者才允许修改
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NO_AUTH_ERROR);
        if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR);
        }
        // 已经改为注解鉴权
//        this.checkPictureAuth(oldPicture, loginUser);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }


    @Async
    @Override
    public void deleteSpaceAndPicture(long spaceId, User loginUser) {
        List<Picture> list = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .list();
        if (list.size() <= 0) {
            return;
        }
        // 获取图片的url和thumbnailUrl
        List<String> collect = list.stream()
                .map(picture -> picture.getUrl())
                .collect(Collectors.toList());
        cosManager.deleteObjects(collect);
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1、校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR);
        // 2、校验权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无空间权限");
        }
        // 3、查询该空间下的所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getPicColor, picColor)
                .isNotNull(Picture::getPicColor)
                .list();
        if (CollectionUtil.isEmpty(pictureList)) {
            return new ArrayList<>();
        }
        // 4、计算相似度并返回
        Color decode = Color.decode(picColor); // 将颜色字符串转换为Color对象
        List<Picture> sortedPictureList = pictureList.stream()
                .sorted(Comparator.comparing(picture -> {
                    String picturePicColor = picture.getPicColor();
                    if (StrUtil.isBlank(picturePicColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color color = Color.decode(picturePicColor);
                    return -calculateSimilarity(color, decode);
                }))
                .limit(10)
                .collect(Collectors.toList());
        return sortedPictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    /**
     * @param pictureEditByBatchRequest
     * @param loginUser
     */

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 1、校验参数
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String category = pictureEditByBatchRequest.getCategory();
        if (spaceId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR);
        // 2、空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无空间权限");
        }
        // 3、指定图片是否存在
        List<Picture> list = this.lambdaQuery()
                .in(Picture::getId, pictureIdList)
                .eq(Picture::getSpaceId, spaceId)
                .list();
        if (list == null || list.size() == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        // 4、更新分类和标签
        list.forEach(picture -> {
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
            if (StrUtil.isNotEmpty(category)) {
                picture.setCategory(category);
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureNameRule(list, nameRule);
        // 5、更新数据库
        boolean update = this.updateBatchById(list);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);


    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param list
     * @param nameRule
     */

    private void fillPictureNameRule(List<Picture> list, String nameRule) {
        if (StrUtil.isBlank(nameRule) || CollUtil.isEmpty(list)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : list) {
                String name = nameRule.replaceAll("\\{序号}", String.valueOf(count));
                picture.setName(name);
                count++;
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量重命名失败");
        }


    }

    /**
     * 创建图像扩展任务请求
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 1、校验参数
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR, "图片id不能为空");
        Picture picture = Optional.ofNullable(this.getById(pictureId)).orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));
        // 已经改为注解鉴权
//        checkPictureAuth(picture, loginUser);
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(createPictureOutPaintingTaskRequest.getParameters());

        // 创建任务
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }



}




